package com.Gehaltsrechner;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.Toast;



public class GehaltsrechnerActivity extends TabActivity
{
  private TabHost tabHost;
  public static Context con;
  
  public NeuerMonat neubeginn;
  
  public File file = new File("/sdcard/SalaryCalculator.txt");

  public void onCreate(Bundle savedInstanceState) 
  {
      super.onCreate(savedInstanceState);   
      setContentView(R.layout.tab);
      
      startApp();
  }
   
  public void startApp()
  {
  	//Damit Datenbank geladen werden kann
    con = this.getApplicationContext ();
    
    new Sprache(getResources ());
    
    tabHost = getTabHost();  
    Resources res = getResources(); 
    TabHost.TabSpec spec;  
    Intent intent;  
    
    intent = new Intent().setClass(this, Rechner.class);
    spec = tabHost.newTabSpec(null)
    		.setIndicator("",
            res.getDrawable(R.drawable.icon))
        .setContent(intent);
    tabHost.addTab(spec);
    
    intent = new Intent().setClass(this, Tabelle.class);
    spec = tabHost.newTabSpec(null)
    		.setIndicator("",//Sprache.eintrag,
            res.getDrawable(R.drawable.tabelle))
        .setContent(intent);
    tabHost.addTab(spec);
    
//    DiagrammAcrivity act = new DiagrammAcrivity ();
//    intent = act.execute (this.getApplicationContext ());
//    spec = tabHost.newTabSpec(null)
//    		.setIndicator("",
//            res.getDrawable(R.drawable.diagramm))
//        .setContent(intent);
//    tabHost.addTab(spec);
    
    intent = new Intent().setClass(this, Einstellung.class);
    spec = tabHost.newTabSpec(null)
    		.setIndicator("",//Sprache.einstellung,
            res.getDrawable(R.drawable.einstellung))
        .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);
  }
  
  public static void init ()
  {
  	Rechner.anzahl = 0;
  	Rechner.gesamtverdienst = 0;
  	Rechner.fillMaps = new ArrayList<HashMap<String, String>>();
  }
  
  /**
   * Bei betaetigen des Menubutton wird ein Menu erzeugt
   */
  public boolean onCreateOptionsMenu(Menu menu) 
  {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.layout.menu, menu);
    return true;
  }
  
  /**
   * Wird festgelegt was im Menu passieren soll 
   */
  public boolean onOptionsItemSelected(MenuItem item) 
  {
    switch (item.getItemId()) 
    {
    		case R.id.income:  
    		{
    			if(Einstellung.exist ("6") > 0)
    			{
    				Date dt = new Date();
    				SimpleDateFormat year = new SimpleDateFormat("yyyy");          	
    				SimpleDateFormat month = new SimpleDateFormat("MM");
        	
    				Dateimanager datei = new Dateimanager ();
    				int tag = Integer.parseInt (Einstellung.select (6));
    				int monat = Integer.parseInt (month.format(dt));
    				int jahr = Integer.parseInt (year.format(dt));
    				datei.liesAusDatei(tag + 1, monat - 1, jahr); 

    				alterDialog (Sprache.gesamtverdienst + ":("+ (monat - 1) + "/" + jahr +  ") = " + Rechner.gesamtverdienst);
    			}
    			else
    			{
    				alterDialog (Sprache.festlegen);
    			}
    			break;
    		}
        case R.id.neuerMonat:  
        {
        	neuenMonatbeginnen ();
        	break;
        }
        case R.id.help:  
        {
        	 // prepare the alert box
          AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

          // set the message to display
          alertbox.setMessage(Sprache.informationstext);

          // add a neutral button to the alert box and assign a click listener
          alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() 
          {
              // click listener on the alert box
              public void onClick(DialogInterface arg0, int arg1) 
              {
              }
          });

          // show it
          alertbox.show();          
        	break;
        }
        case R.id.export:  
        {
      		AlertDialog.Builder alert = new AlertDialog.Builder(GehaltsrechnerActivity.this);		
      		alert.setTitle("Export as PDF");
      		alert.setMessage(Sprache.pdf);

      		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
      		{
      			public void onClick(DialogInterface dialog, int whichButton) 
      			{
      				try
      				{
      					pdfErzeugen ();
      				}
    					catch (Exception e)
    					{
    						alterDialog("Problems at creating the PDF.");
    					}
      		  }
      		});
      		alert.setNegativeButton (Sprache.abbrechen, new DialogInterface.OnClickListener()
      		{
      			public void onClick(DialogInterface dialog, int whichButton) 
      			{
      		  }
      		});
      		alert.show ();  
        	break;
        }

    }
    return true;
  }
  
  public void neuenMonatbeginnen()
  {
  	neubeginn = new NeuerMonat(this, "");
  	neubeginn.show();
  	
  	neubeginn.ja.setOnClickListener(new View.OnClickListener() 
    {
      public void onClick(View v) 
      {
       	Rechner.fillMaps = new ArrayList<HashMap<String, String>>();
    
       	//Datenbank leeren 
       	SQLiteDatabase db = null;
    		Eintraege data = new Eintraege(GehaltsrechnerActivity.con);
    		db = data.getWritableDatabase ();
       	db.delete (Eintraege.DATENBANK_NAME, null, null);
       	db.close ();
        	
        neubeginn.closeDialog();
       	Rechner.gesamtverdienst = 0;
       	Rechner.anzahl = 0;
       	
       	monatsdialog ();
      }
    });
  	neubeginn.nein.setOnClickListener(new View.OnClickListener() 
    {
       public void onClick(View v) 
       {
        	neubeginn.closeDialog();
       }
    });
  }
  
  /**
   * Der Nutzer bekommt mitgeteilt das er alle Eintraege geloescht hat.
   */
  public void monatsdialog ()
	{
		Toast.makeText(this, Sprache.neustart, Toast.LENGTH_LONG).show();
		finish();
	}
  
  public void alterDialog (String dialog)
	{
		AlertDialog.Builder alert = new AlertDialog.Builder(GehaltsrechnerActivity.this);		
		alert.setTitle("Dialog");
		alert.setMessage(dialog);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int whichButton) 
			{
				
		  }
		});
		alert.show ();
	}

  public void pdfErzeugen() throws Exception 
  {
  	String newFolder = "/Salarycalculator";
  	String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
  	File myNewFolder = new File(extStorageDirectory + newFolder);
  	myNewFolder.mkdir();
  	File file = new File("/sdcard/Salarycalculator/Salarycalculator.pdf");
  	
  	Dateimanager datei = new Dateimanager();
  	datei.liesAusDatei ();

  	if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
    {
     		alterDialog("You need an SD-Card to use this function");
    }
    else
    {
  		FileOutputStream file2 = new FileOutputStream(file);
    	Document document = new Document();
    	PdfWriter.getInstance(document, file2);
    	document.open();

    	PdfPTable table = new PdfPTable(3); // Code 1

    	table.addCell("Start");
    	table.addCell(Sprache.ende);
    	table.addCell(Sprache.verdienst);

    	for(int n = 0; n < Rechner.fillMaps.size(); n++)
    	{
    		table.addCell(Rechner.fillMaps.get(n).get("Start"));
    		table.addCell(Rechner.fillMaps.get(n).get("Ende"));
    		table.addCell(Rechner.fillMaps.get(n).get("Verdienst"));
    	}
    	
    	document.add(table);
    	document.close();
    	file2.close();
    	
    	if (file.exists())
    	{
    		Uri path = Uri.fromFile(file);
    		Intent intent = new Intent(Intent.ACTION_VIEW);
    		intent.setDataAndType(path, "application/pdf");
    		intent.putExtra(Intent.EXTRA_STREAM, path);

    		try
    		{
    			startActivity(intent);
    		}
    		catch (ActivityNotFoundException e)
    		{
    			path = Uri.fromFile(file);
      		intent = new Intent(Intent.ACTION_SEND);
      		intent.setDataAndType(path, "application/pdf");
      		intent.putExtra(Intent.EXTRA_STREAM, path);
      		startActivity(intent);
    		}
    	}
    }
  }
}
